package com.chuanyang.driverh.utils.push;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.RecodeState;
import com.chuanyang.driverh.bean.NoticeBean;
import com.chuanyang.driverh.bean.PushData;
import com.chuanyang.driverh.mainhome.CommonNoticeActivity;
import com.chuanyang.driverh.mainhome.SystemMessageActivity;
import com.chuanyang.driverh.mainorder.ReceiveOrderActivity;
import com.chuanyang.driverh.mainother.DialogActivity;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.OrderDetailData;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.ForegroundCallbacks;
import com.chuanyang.driverh.utils.JsonUtil;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.SpeedUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.PushDataEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshMessageEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTTransmitMessage;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
 * onReceiveMessageData 处理透传消息<br>
 * onReceiveClientId 接收 cid <br>
 * onReceiveOnlineState cid 离线上线通知 <br>
 * onReceiveCommandResult 各种事件处理回执 <br>
 */
public class MyIntentService extends GTIntentService {
    public Context mcontext;
    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
     */
    private String data;
    private OrderDetailData.PassPointsBean beginPalace;
    private OrderDetailData.PassPointsBean endPalace;
    private String content;
    private PushData pushData;
    private OrderDetailData orderDetailData;
    private NoticeBean noticeBean;
    private Intent intent;

    public MyIntentService() {

    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
        Log.d(TAG, "onReceiveServicePid -> " + pid);
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        mcontext = context;
        byte[] payload = msg.getPayload();
        if (payload != null) {
            data = new String(payload);
            pushData = JsonUtil.parseJsonToBean(data, PushData.class);
            LogUtils.e("pushData", data + "----");
            //匹配单和app端的指定单，推送给个人为1，车队为2,运输计划里的专线单为3
            //网页发送的指定单为3
            if (pushData.getType() == 1 || pushData.getType() == 2 || pushData.getType() == 3) {
                //下面两条是为了防止推送混乱。
                if (pushData.getType()==1  && !StringUtil.isBlank( SharedPrefUtil.getFleetId())){
                    return;
                }
                if (pushData.getType()==2  && StringUtil.isBlank( SharedPrefUtil.getFleetId())){
                    return;
                }


                if (ForegroundCallbacks.get(mcontext).isForeground()) {
                    //如果有一个未过时的匹配订单，则不需要弹出接受订单的页面
                    //如果orderActivity已经开启，需要先关闭
                    // EventBus.getDefault().post(new OrderFinish());
                    LogUtils.e("pushData", data + "----");
                    //如果是指定
                    if (!RecodeState.isReceiveOrderOpenning()) {  //表示接收订单页面是关闭状态时
                        Intent intent1 = new Intent(mcontext, ReceiveOrderActivity.class);
                        intent1.putExtra("pushdata", pushData);
                        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mcontext.startActivity(intent1);
                    } else { //表示接收订单页面为打开转态时，此时只需要刷新数据
                        EventBus.getDefault().post(new PushDataEvent(pushData));
                        LogUtils.e("ReceiveActivity", "表示接收订单页面为打开转态时-------");
                    }
                } else if (ForegroundCallbacks.get(mcontext).isBackground()) {
                    LogUtils.e("ReceiveActivity", "isBackground-------");
                    getData();
                }
            } else if (pushData.getType() == 4 || pushData.getType() == 5 || pushData.getType() == 6)//货主选择司机4；车队长分配运单(会推送waybillid)5;//司机确认收货推送给车队长6(只有分配的成员全都收货时,车队长才能收到这个推送传入的waybillId)
            {
                if (ForegroundCallbacks.get(mcontext).isForeground()) {
                    openNoticePage();

                } else {
                    noticeDriver(pushData);
                }

            } else if (pushData.getType() == 7)//自定义推送
            {
                noticeSubscrib(pushData);
            } else if (pushData.getType() == 8)//推送来的消息 此处需要记录消息的数目和类型
            {
                SharedPrefUtil.setPreferences("messagecontent" + SharedPrefUtil.getUserId(), pushData.getNews());
                //PreferencesUtil.setPreferences(context, "time"+PrefUtils.getInstance(mcontext).getUserId(), TimeUtils.getForamtTime("MM-dd HH:mm"));
                SharedPrefUtil.setPreferences("time" + SharedPrefUtil.getUserId(), System.currentTimeMillis());

                if (SharedPrefUtil.getPreferences("messagecount" + SharedPrefUtil.getUserId(), 0) != null) {
                    SharedPrefUtil.setPreferences("messagecount" + SharedPrefUtil.getUserId(), SharedPrefUtil.getPreferences("messagecount" + SharedPrefUtil.getUserId(), 0) + 1);
                } else {
                    SharedPrefUtil.setPreferences("messagecount" + SharedPrefUtil.getUserId(), 1);
                }
//应用处于前台 直接通知刷新
                if (ForegroundCallbacks.get(mcontext).isForeground())
                {
                    EventBus.getDefault().post(new RefleshMessageEvent(true, 0));
                } else {
                    noticeSystemMessage(pushData);
                    EventBus.getDefault().post(new RefleshMessageEvent(true, 0));

                }
                //处于后台时只需要在进入app时显示
            }
        }
    }

    private void openNoticePage() {

        switch (pushData.getType()) {
            case 4:
                noticeBean = new NoticeBean("有货主选择了你，可点击查看！", "取消", "查看", pushData.getOrderId() + "", pushData.getType());
                break;
            case 5:
                noticeBean = new NoticeBean("车队长已向您分配了运单，可点击查看！", "取消", "查看", pushData.getWaybillId() + "", pushData.getType());
                break;
            case 6:
                noticeBean = new NoticeBean("您分配给队员的运单已确认卸货，可点击查看！", "取消", "查看", pushData.getWaybillId() + "", pushData.getType());

                break;

        }
        Intent intent2 = new Intent(mcontext, CommonNoticeActivity.class);
        intent2.putExtra("data", noticeBean);
        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mcontext.startActivity(intent2);
    }


    private void noticeSystemMessage(PushData pushData) {
        content = "";
        if (!TextUtils.isEmpty(pushData.getNews())) {
            content = pushData.getNews();
            //(1)获取通知的管理者
            NotificationManager nm = (NotificationManager) mcontext.getSystemService(Context.NOTIFICATION_SERVICE);
            intent = new Intent(mcontext, SystemMessageActivity.class);
            intent.putExtra("type", 1);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(mcontext, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            Notification.Builder builder = new Notification.Builder(mcontext)
                    .setTicker("系统消息")
                    .setAutoCancel(true)
                    .setContentTitle("系统消息")
                    .setContentText(content)
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.mipmap.icon1)
                    .setWhen(System.currentTimeMillis())
                    .setLights(0xff0000ff, 300, 0)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setOngoing(true);
            Notification notification = builder.getNotification();
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            nm.notify(222, notification);
        }
    }

    //获取推送来的订单信息
    private void getData() {
        PushData pushData = JsonUtil.parseJsonToBean(data, PushData.class);
        DialogUtil.showLoadingDialog(mcontext, null);
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", pushData.getOrderId() + "");
        MyHttpUtil.selectOrderMsgById(mcontext, params, new MyCallback<OrderDatailResult>(mcontext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    orderDetailData = result.getData();
                    parseData(orderDetailData);
                } else {
                }
            }
        });
    }

    /**
     * 播报订单内容
     */
    private void invoceOrderContent(OrderDetailData.PassPointsBean beginPalace, OrderDetailData.PassPointsBean endPalace) {
        content = "";
        content = "您有新的订单从" + beginPalace.getProvince() + beginPalace.getCity() + beginPalace.getRegions()
                + "到" + endPalace.getProvince() + endPalace.getCity() + endPalace.getRegions() + "请您接单";
        SpeedUtil.broadcastOrder(mcontext, content);
    }

    private void parseData(OrderDetailData data) {
        for (OrderDetailData.PassPointsBean bean : data.getPassPoints()) {
            if (bean.getPointType().equals("s")) {
                beginPalace = bean;
            } else if (bean.getPointType().equals("e")) {
                endPalace = bean;
            }

        }
        invoceOrderContent(beginPalace, endPalace);
        receiverOrderNotify(ReceiveOrderActivity.class, "你有新订单", pushData, orderDetailData);

    }

    //提示用户接单或者查看订单
    private void receiverOrderNotify(Class<?> actclass, String title, PushData pushData, OrderDetailData orderDetailData) {
        String descibe = "";
        if (pushData.getType() == 3) {
            descibe = "您有一个分配订单，请查看！";
        } else {
            if (orderDetailData.getOrder_type() == 2)//匹配订单
            {
                descibe = "您有一个匹配订单，请接收!";
            } else {
                descibe = "您有一个专线订单，请接收!";

            }
        }
        //创建一个意图对象
        Intent intent = new Intent(mcontext, actclass);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("pushdata", pushData);
        intent.putExtra("OrderDetailData", orderDetailData);
        //(1)获取通知的管理者
        NotificationManager nm = (NotificationManager) mcontext.getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getActivity(mcontext, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification.Builder builder = new Notification.Builder(mcontext)
                .setTicker("订单通知")
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentText(descibe)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.mipmap.icon1)
                .setWhen(System.currentTimeMillis())
                .setLights(0xff0000ff, 300, 0)
//                .setDefaults(Notification.DEFAULT_SOUND)
                .setOngoing(true);
        Notification notification = builder.getNotification();
        nm.notify(222, notification);
    }

    private void noticeDriver(PushData pushData) {
        content = "";
        switch (pushData.getType()) {
            case 4:
                content = "您申请的订单,已被货主选中!";
                break;
            case 5:
                content = "车队长已向您分配了运单!";
                break;
            case 6:
                content = "您分配给队员的订单,已确认卸货!";
                break;

        }
        SpeedUtil.broadcastOrder(mcontext, content);
        //(1)获取通知的管理者
        NotificationManager nm = (NotificationManager) mcontext.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(mcontext)
                .setTicker("订单通知")
                .setAutoCancel(true)
                .setContentTitle("订单提醒")
                .setContentText(content)
                .setSmallIcon(R.mipmap.icon1)
                .setWhen(System.currentTimeMillis())
                .setLights(0xff0000ff, 300, 0)
//                .setDefaults(Notification.DEFAULT_SOUND)
                .setOngoing(true);
        Notification notification = builder.getNotification();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        nm.notify(222, notification);
    }

    private void noticeSubscrib(PushData pushData) {
        content = "";
        if (!TextUtils.isEmpty(pushData.getNews())) {
            content = pushData.getNews();
            SpeedUtil.broadcastOrder(mcontext, content);
            //(1)获取通知的管理者
         /*   NotificationManager nm = (NotificationManager) mcontext.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(mcontext)
                    .setTicker("订阅通知")
                    .setAutoCancel(true)
                    .setContentTitle("订阅提醒")
                    .setContentText(content)
                    .setSmallIcon(R.mipmap.icon1)
                    .setWhen(System.currentTimeMillis())
                    .setLights(0xff0000ff, 300, 0)
//                .setDefaults(Notification.DEFAULT_SOUND)
                    .setOngoing(true);
            Notification notification = builder.getNotification();
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            nm.notify(222, notification);*/



            Intent intent2 = new Intent(mcontext, DialogActivity.class);
            intent2.putExtra("data", content);
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mcontext.startActivity(intent2);


//
//          Dialog dialog= DialogUtil.alertDialog(BaseApplication.getInstance().getActivity(),content);
//            dialog.show();
        }
    }


    @Override
    public void onReceiveClientId(Context context, String clientid) {
        Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
//        sendMessage(clientid, 1);
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        Log.d(TAG, "onReceiveOnlineState -> " + (online ? "online" : "offline"));
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        Log.d(TAG, "onReceiveCommandResult -> " + cmdMessage);
  /*
        int action = cmdMessage.getAction();

        if (action == PushConsts.SET_TAG_RESULT) {
            setTagResult((SetTagCmdMessage) cmdMessage);
        } else if ((action == PushConsts.THIRDPART_FEEDBACK)) {
            feedbackResult((FeedbackCmdMessage) cmdMessage);
        }*/
    }


}
